package com.shali.wechat.order.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shali.wechat.order.client.ProductFeignClient;
import com.shali.wechat.order.dto.CartDTO;
import com.shali.wechat.order.dto.OrderDTO;
import com.shali.wechat.order.entity.OrderDetail;
import com.shali.wechat.order.entity.OrderMaster;
import com.shali.wechat.order.entity.ProductInfo;
import com.shali.wechat.order.enums.OrderStautsEnum;
import com.shali.wechat.order.enums.PayStautsEnum;
import com.shali.wechat.order.repository.OrderDetailRepository;
import com.shali.wechat.order.repository.OrderMasterRepository;
import com.shali.wechat.order.service.OrderService;
import com.shali.wechat.order.utils.KeyUtil;
@Service	
public class OrderServiceImpl implements OrderService{

	@Autowired
	private OrderMasterRepository orderMasterRepository;
	@Autowired
	private OrderDetailRepository orderDetailRepository;
	@Autowired
	private ProductFeignClient productFeignClient;
	
	//TODO 查询商品信息(调用商品微服务)
	//TODO 计算总价
	//TODO 扣库存
	//订单入库
	@Override
	@Transactional
	public OrderDTO create(OrderDTO orderDTO) {
		
		String orderId = KeyUtil.genUniqueKey();
		
		//查询商品信息(调用商品微服务)
		List<String> ids = orderDTO.getOrderDetail().stream()
				.map(OrderDetail::getProductId)
				.collect(Collectors.toList());
		
		List<ProductInfo> productInfoList = productFeignClient.getProductInfoList(ids);
		//计算总价
		BigDecimal orderAmout = new BigDecimal(BigInteger.ZERO);
		for(OrderDetail orderDetail:orderDTO.getOrderDetail()) {
			for(ProductInfo productInfo:productInfoList) {
				
				if(productInfo.getProductId().equals(orderDetail.getProductId())) {
					orderAmout = productInfo.getProductPrice()
							.multiply(new BigDecimal(orderDetail.getProductQuantity()))
							.add(orderAmout);
					BeanUtils.copyProperties(productInfo, orderDetail);
					orderDetail.setOrderId(orderId);
					orderDetail.setDetailId(KeyUtil.genUniqueKey());
					//订单详情入库
					orderDetailRepository.save(orderDetail);
				}
			}
		}
		//扣库存
		List<CartDTO> cartDTOList = orderDTO.getOrderDetail().stream()
				.map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
				.collect(Collectors.toList());
		productFeignClient.decreaseStock(cartDTOList);
		//拷贝属性
		OrderMaster orderMaster = new OrderMaster();
		orderDTO.setOrderId(orderId);
		BeanUtils.copyProperties(orderDTO, orderMaster);
		
		orderMaster.setOrderAmount(orderAmout);
		orderMaster.setOrderStatus(OrderStautsEnum.NEW.getCode());
		orderMaster.setPayStatus(PayStautsEnum.WAIT.getCode());
		//订单入库
		orderMasterRepository.save(orderMaster);
		return orderDTO;
	}
}
